package com.gmail.genzouw.gconv

import org.mozilla.universalchardet.Constants

class Gconv{
	private detector = null

	class Charset{
		private Charset(){}
		static final String ISO_2022_JP = Constants.CHARSET_ISO_2022_JP
		static final String ISO_2022_CN = Constants.CHARSET_ISO_2022_CN
		static final String ISO_2022_KR = Constants.CHARSET_ISO_2022_KR
		static final String ISO_8859_5 = Constants.CHARSET_ISO_8859_5
		static final String ISO_8859_7 = Constants.CHARSET_ISO_8859_7
		static final String ISO_8859_8 = Constants.CHARSET_ISO_8859_8
		static final String BIG5 = Constants.CHARSET_BIG5
		static final String GB18030 = Constants.CHARSET_GB18030
		static final String EUC_JP = Constants.CHARSET_EUC_JP
		static final String EUC_KR = Constants.CHARSET_EUC_KR
		static final String EUC_TW = Constants.CHARSET_EUC_TW
		static final String SHIFT_JIS = Constants.CHARSET_SHIFT_JIS
		static final String IBM855 = Constants.CHARSET_IBM855
		static final String IBM866 = Constants.CHARSET_IBM866
		static final String KOI8_R = Constants.CHARSET_KOI8_R
		static final String MACCYRILLIC = Constants.CHARSET_MACCYRILLIC
		static final String WINDOWS_1251 = Constants.CHARSET_WINDOWS_1251
		static final String WINDOWS_1252 = Constants.CHARSET_WINDOWS_1252
		static final String WINDOWS_1253 = Constants.CHARSET_WINDOWS_1253
		static final String WINDOWS_1255 = Constants.CHARSET_WINDOWS_1255
		static final String UTF_8 = Constants.CHARSET_UTF_8
		static final String UTF_16BE = Constants.CHARSET_UTF_16BE
		static final String UTF_16LE = Constants.CHARSET_UTF_16LE
		static final String UTF_32BE = Constants.CHARSET_UTF_32BE
		static final String UTF_32LE  = Constants.CHARSET_UTF_32LE
	}

	private static Gconv SELF = new Gconv()

	private Gconv(){
		detector = new org.mozilla.universalchardet.UniversalDetector()
	}

	static Gconv getInstance(){
		SELF
	}

	String guess(byte[] bytes){
		detector.with{
			reset()
			handleData(bytes as byte[], 0, bytes.size())
			dataEnd()
		}

		detector.detectedCharset
	}

	byte[] gconv(byte[] bytes, to){
		this.gconv(bytes, null, to)
	}

	byte[] gconv(byte[] bytes, from, to){
		if( !from ) {
			from = this.guess(bytes)
		}

		from ? new String(bytes, from).getBytes(to) : bytes
	}

	byte[] toEuc(byte[] bytes){
		this.gconv(bytes, Charset.EUC_JP)
	}

	byte[] toSjis(byte[] bytes){
		this.gconv(bytes, Charset.SHIFT_JIS)
	}

	byte[] toUtf8(byte[] bytes){
		this.gconv(bytes, Charset.UTF_8)
	}

	boolean isEuc(byte[] bytes){
		this.guess(bytes) == Charset.EUC_JP
	}

	boolean isSjis(byte[] bytes){
		this.guess(bytes) == Charset.SHIFT_JIS
	}

	boolean isUtf8(byte[] bytes){
		this.guess(bytes) == Charset.UTF_8
	}

}
